//
//  ContactViewController.m
//  mutiThread
//
//  Created by xiaoxiaojia on 17/4/11.
//  Copyright (c) 2017年 admin. All rights reserved.
//

#import "ContactViewController.h"

#import "KCContact.h"
#import "KCContactGroup.h"

@interface ContactViewController ()<UITableViewDataSource>{
	UITableView *_tableView;
	NSMutableArray *_contacts;//联系人模型 
	NSIndexPath *_selectedIndexPath;//当前选中的组和行
}

@end

@implementation ContactViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	
	//初始化数据
	[self initData];
	
	//创建一个分组样式的UITableView
	_tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
	
	//设置数据源，注意必须实现对应的UITableViewDataSource协议
	_tableView.dataSource=self;
	//设置代理
	_tableView.delegate=self;
	
	[self.view addSubview:_tableView];
}

#pragma mark 加载数据
-(void)initData{
	_contacts=[[NSMutableArray alloc]init];
	
	KCContact *contact1=[KCContact initWithFirstName:@"Cui" andLastName:@"Kenshin" andPhoneNumber:@"18500131234"];
	KCContact *contact2=[KCContact initWithFirstName:@"Cui" andLastName:@"Tom" andPhoneNumber:@"18500131237"];
	KCContactGroup *group1=[KCContactGroup initWithName:@"C" andDetail:@"With names beginning with C" andContacts:[NSMutableArray arrayWithObjects:contact1,contact2, nil]];
	[_contacts addObject:group1];
	
	
	
	KCContact *contact3=[KCContact initWithFirstName:@"Lee" andLastName:@"Terry" andPhoneNumber:@"18500131238"];
	KCContact *contact4=[KCContact initWithFirstName:@"Lee" andLastName:@"Jack" andPhoneNumber:@"18500131239"];
	KCContact *contact5=[KCContact initWithFirstName:@"Lee" andLastName:@"Rose" andPhoneNumber:@"18500131240"];
	KCContactGroup *group2=[KCContactGroup initWithName:@"L" andDetail:@"With names beginning with L" andContacts:[NSMutableArray arrayWithObjects:contact3,contact4,contact5, nil]];
	[_contacts addObject:group2];
	
	
	
	KCContact *contact6=[KCContact initWithFirstName:@"Sun" andLastName:@"Kaoru" andPhoneNumber:@"18500131235"];
	KCContact *contact7=[KCContact initWithFirstName:@"Sun" andLastName:@"Rosa" andPhoneNumber:@"18500131236"];
	
	KCContactGroup *group3=[KCContactGroup initWithName:@"S" andDetail:@"With names beginning with S" andContacts:[NSMutableArray arrayWithObjects:contact6,contact7, nil]];
	[_contacts addObject:group3];
	
	
	KCContact *contact8=[KCContact initWithFirstName:@"Wang" andLastName:@"Stephone" andPhoneNumber:@"18500131241"];
	KCContact *contact9=[KCContact initWithFirstName:@"Wang" andLastName:@"Lucy" andPhoneNumber:@"18500131242"];
	KCContact *contact10=[KCContact initWithFirstName:@"Wang" andLastName:@"Lily" andPhoneNumber:@"18500131243"];
	KCContact *contact11=[KCContact initWithFirstName:@"Wang" andLastName:@"Emily" andPhoneNumber:@"18500131244"];
	KCContact *contact12=[KCContact initWithFirstName:@"Wang" andLastName:@"Andy" andPhoneNumber:@"18500131245"];
	KCContactGroup *group4=[KCContactGroup initWithName:@"W" andDetail:@"With names beginning with W" andContacts:[NSMutableArray arrayWithObjects:contact8,contact9,contact10,contact11,contact12, nil]];
	[_contacts addObject:group4];
	
	
	KCContact *contact13=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joy" andPhoneNumber:@"18500131246"];
	KCContact *contact14=[KCContact initWithFirstName:@"Zhang" andLastName:@"Vivan" andPhoneNumber:@"18500131247"];
	KCContact *contact15=[KCContact initWithFirstName:@"Zhang" andLastName:@"Joyse" andPhoneNumber:@"18500131248"];
	KCContactGroup *group5=[KCContactGroup initWithName:@"Z" andDetail:@"With names beginning with Z" andContacts:[NSMutableArray arrayWithObjects:contact13,contact14,contact15, nil]];
	[_contacts addObject:group5];
	
}

#pragma mark - 数据源方法
#pragma mark 返回分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	NSLog(@"计算分组数");
	return _contacts.count;
}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	NSLog(@"计算每组(组%i)行数",section);
	KCContactGroup *group1=_contacts[section];
	return group1.contacts.count;
}

#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	//NSIndexPath是一个结构体，记录了组和行信息
	KCContactGroup *group=_contacts[indexPath.section];
	KCContact *contact=group.contacts[indexPath.row];
	static NSString* inentifier=@"TableCell";
	UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:inentifier ];
	if(!cell){
	 cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
	}
	cell.textLabel.text=[contact getName];
	NSURL *imgUrl=[NSURL URLWithString:[NSString stringWithFormat: @"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg",indexPath.row]];
	dispatch_queue_t asynQueue = dispatch_queue_create("获取图片线程", DISPATCH_QUEUE_CONCURRENT);
	dispatch_async(asynQueue, ^{
		NSLog(@"当前线程%@",[NSThread currentThread]);
		NSData *imagedata=[NSData dataWithContentsOfURL:imgUrl];
		UIImage *image=[UIImage imageWithData:imagedata];
		dispatch_queue_t mainQueue= dispatch_get_main_queue();
		dispatch_async(mainQueue, ^{
			[self updateImage:cell withImage:image];
		});
	});
	NSData *imagedata=[NSData dataWithContentsOfURL:imgUrl];
	cell.imageView.image=[UIImage imageWithData:imagedata];
	cell.detailTextLabel.text=contact.phoneNumber;
	cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
	
	NSLog(@"生成单元格(组：%i,行%i) %@",indexPath.section,indexPath.row,cell);//NSLog(@"cell:%@",cell);
	return cell;
}

-(void)updateImage:(UITableViewCell*)cell withImage:(UIImage*)image{
	cell.imageView.image=image;
}

#pragma mark 返回每组头标题名称
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
	NSLog(@"生成组（组%i）名称",section);
	KCContactGroup *group=_contacts[section];
	return group.name;
}

#pragma mark 返回每组尾部说明
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
	NSLog(@"生成尾部（组%i）详情",section);
	KCContactGroup *group=_contacts[section];
	return group.detail;
}

#pragma mark 返回每组标题索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
	NSLog(@"生成组索引");
	NSMutableArray *indexs=[[NSMutableArray alloc]init];
	for(KCContactGroup *group in _contacts){
		[indexs addObject:group.name];
	}
	return indexs;
}

#pragma mark - 代理方法
#pragma mark 设置分组标题内容高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	if(section==0){
		return 50;
	}
	return 40;
}

#pragma mark 设置每行高度（每行高度可以不一样）
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return 45;
}

#pragma mark 设置尾部说明内容高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
	return 40;
}

#pragma mark 点击行
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	_selectedIndexPath=indexPath;
	KCContactGroup *group=_contacts[indexPath.section];
	KCContact *contact=group.contacts[indexPath.row];
	//创建弹出窗口
	UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"System Info" message:[contact getName] delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
	alert.alertViewStyle=UIAlertViewStylePlainTextInput; //设置窗口内容样式
	UITextField *textField= [alert textFieldAtIndex:0]; //取得文本框
	textField.text=contact.phoneNumber; //设置文本框内容
	[alert show]; //显示窗口
}

#pragma mark 窗口的代理方法，用户保存数据
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	//当点击了第二个按钮（OK）
	if (buttonIndex==1) {
		UITextField *textField= [alertView textFieldAtIndex:0];
		//修改模型数据
		KCContactGroup *group=_contacts[_selectedIndexPath.section];
		KCContact *contact=group.contacts[_selectedIndexPath.row];
		contact.phoneNumber=textField.text;
		//刷新表格
		NSArray *indexPaths=@[_selectedIndexPath];//需要局部刷新的单元格的组、行
		[_tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];//后面的参数代码更新时的动画
	}
}


#pragma mark 重写状态样式方法
-(UIStatusBarStyle)preferredStatusBarStyle{
	return UIStatusBarStyleLightContent;
}


#pragma mark 切换开关转化事件
-(void)switchValueChange:(UISwitch *)sw{
	NSLog(@"section:%i,switch:%i",sw.tag, sw.on);
}
@end



